// pages/volunteer/orders.js
Page({
  data: {
    // 订单列表
    orders: [
      {
        id: 1,
        orderNo: 'RD20231201001',
        productId: 1,
        productName: '马克杯',
        productImage: '/images/杯子.png',
        quantity: 2,
        points: 100,
        status: 'pending',
        statusText: '待发货',
        createTime: '2023-12-01 14:30:25',
        address: {
          name: '张三',
          phone: '13800138000',
          province: '湖南省',
          city: '长沙市',
          district: '岳麓区',
          detail: '麓谷企业广场A座1001室'
        },
        trackingNumber: null,
        estimatedDelivery: '2023-12-08'
      },
      {
        id: 2,
        orderNo: 'RD20231128002',
        productId: 2,
        productName: '马克杯',
        productImage: '/images/1.jpg',
        quantity: 1,
        points: 60,
        status: 'shipped',
        statusText: '已发货',
        createTime: '2023-11-28 09:15:30',
        address: {
          name: '李四',
          phone: '13900139000',
          province: '湖南省',
          city: '长沙市',
          district: '开福区',
          detail: '五一广场地铁站附近'
        },
        trackingNumber: 'SF1234567890',
        estimatedDelivery: '2023-12-05'
      },
      {
        id: 3,
        orderNo: 'RD20231125003',
        productId: 4,
        productName: '马克杯',
        productImage: '/images/杯子.png',
        quantity: 1,
        points: 70,
        status: 'completed',
        statusText: '已完成',
        createTime: '2023-11-25 16:45:12',
        address: {
          name: '王五',
          phone: '13700137000',
          province: '湖南省',
          city: '长沙市',
          district: '天心区',
          detail: '黄兴路步行街附近'
        },
        trackingNumber: 'YT0987654321',
        estimatedDelivery: '2023-12-02'
      }
    ],
    
    // 筛选状态
    currentStatus: 'all',
    filteredOrders: [],
    
    // 页面状态
    loading: false,
    hasMore: false,
    currentPage: 1,
    pageSize: 10,
    
    // 弹窗状态
    showOrderModal: false,
    selectedOrder: null
  },

  onLoad(options) {
    this.loadOrders();
    this.filterOrders();
  },

  onShow() {
    this.refreshOrders();
  },

  // 加载订单数据
  loadOrders() {
    const orders = wx.getStorageSync('volunteerOrders') || [];
    if (orders.length > 0) {
      this.setData({ orders });
    }
  },

  // 刷新订单
  refreshOrders() {
    this.loadOrders();
    this.filterOrders();
  },

  // 筛选订单
  filterOrders(e) {
    const status = e ? e.currentTarget.dataset.status : this.data.currentStatus;
    
    let filteredOrders = this.data.orders;
    if (status !== 'all') {
      filteredOrders = this.data.orders.filter(order => order.status === status);
    }
    
    this.setData({
      currentStatus: status,
      filteredOrders: filteredOrders
    });
  },

  // 查看订单详情（弹窗形式）
  viewOrderDetail(e) {
    const orderId = e.currentTarget.dataset.id;
    const order = this.data.orders.find(o => o.id === orderId);
    
    if (order) {
      this.setData({
        selectedOrder: order,
        showOrderModal: true
      });
    }
  },

  // 关闭订单详情弹窗
  closeOrderModal() {
    this.setData({
      showOrderModal: false,
      selectedOrder: null
    });
  },

  // 取消订单
  cancelOrder() {
    const order = this.data.selectedOrder;
    
    if (!order) return;
    
    wx.showModal({
      title: '取消订单',
      content: '确定要取消这个订单吗？取消后积分将退还到您的账户。',
      confirmText: '确定取消',
      cancelText: '再想想',
      success: (res) => {
        if (res.confirm) {
          this.performCancelOrder(order.id);
        }
      }
    });
  },

  // 执行取消订单
  performCancelOrder(orderId) {
    wx.showLoading({
      title: '取消中...'
    });

    setTimeout(() => {
      // 更新订单状态为已取消
      const orders = this.data.orders.map(order => {
        if (order.id === orderId) {
          return {
            ...order,
            status: 'cancelled',
            statusText: '已取消'
          };
        }
        return order;
      });
      
      // 退还积分
      const order = this.data.orders.find(o => o.id === orderId);
      if (order) {
        const userData = wx.getStorageSync('volunteerUserData') || {};
        userData.currentPoints = (userData.currentPoints || 0) + order.points;
        wx.setStorageSync('volunteerUserData', userData);
      }
      
      this.setData({ 
        orders,
        showOrderModal: false,
        selectedOrder: null
      });
      wx.setStorageSync('volunteerOrders', orders);
      this.filterOrders();
      
      wx.hideLoading();
      wx.showToast({
        title: '订单已取消，积分已退还',
        icon: 'success',
        duration: 2000
      });
    }, 1000);
  },

  // 查看物流信息
  viewTracking(e) {
    const orderId = e.currentTarget.dataset.id;
    const order = this.data.orders.find(o => o.id === orderId);
    
    if (order && order.trackingNumber) {
      wx.navigateTo({
        url: `/pages/volunteer/tracking?orderId=${orderId}&trackingNumber=${order.trackingNumber}`
      });
    } else {
      wx.showToast({
        title: '暂无物流信息',
        icon: 'none'
      });
    }
  },

  // 确认收货
  confirmReceived(e) {
    const orderId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '确认收货',
      content: '确认已收到商品吗？',
      confirmText: '确认',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          this.updateOrderStatus(orderId, 'completed');
        }
      }
    });
  },

  // 更新订单状态
  updateOrderStatus(orderId, status) {
    const orders = this.data.orders.map(order => {
      if (order.id === orderId) {
        return {
          ...order,
          status: status,
          statusText: this.getStatusText(status)
        };
      }
      return order;
    });
    
    this.setData({ orders });
    wx.setStorageSync('volunteerOrders', orders);
    this.filterOrders();
    
    wx.showToast({
      title: '操作成功',
      icon: 'success'
    });
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'pending': '待发货',
      'shipped': '已发货',
      'completed': '已完成',
      'cancelled': '已取消'
    };
    return statusMap[status] || '未知状态';
  },

  // 跳转到商城
  goToMall() {
    wx.navigateTo({
      url: '/pages/volunteer/mall'
    });
  },

  // 加载更多订单
  loadMore() {
    if (this.data.loading || !this.data.hasMore) {
      return;
    }
    
    this.setData({ loading: true });
    
    // 模拟加载更多数据
    setTimeout(() => {
      // 这里应该调用实际的API
      this.setData({
        loading: false,
        hasMore: false // 暂时设置为false，实际应该根据API返回结果判断
      });
    }, 1000);
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshOrders();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  }
});